package cn.gov.customs.h2018.service.impl;

import cn.gov.customs.h2018.pojo.Article;
import cn.gov.customs.h2018.service.ParallelQuery;
import cn.gov.customs.h2018.util.EhcacheUtil;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
public class SwjQueryImpl implements ParallelQuery {

    private final String url = "http://jsonplaceholder.typicode.com/posts/";

    @Autowired
    RestTemplate rest;

    @Autowired
    private EhcacheUtil ehcacheUtil;

    @Override
    public List<Article> query(int articleCount) {
        List<Article> result = Lists.newArrayList();

        for (int i = 0; i < articleCount; i++) {
            if (ehcacheUtil.get(i) == null) {
                ResponseEntity<Article> temp = rest.getForEntity(url + (i + 1), Article.class);
                ehcacheUtil.set(i, temp.getBody(), 120);
                result.add(temp.getBody());
            } else {
                Article cacheValue = (Article) ehcacheUtil.get(i);
                result.add(cacheValue);
            }
        }
        return result;
    }
}
